﻿#include "StdAfx.h"

EDMain::EDMain(HINSTANCE hInst /*= GetModuleHandle(NULL)*/)
{
	m_pMainWnd.Attach(new EDMainWnd);
	InitMain();
}

EDMain::~EDMain()
{
	UnInitMain();
}

bool EDMain::InitMain()
{
	bool bRet = false;
	do 
	{
		RunPrepare();
		if (false == RunMainUI())
		{
			break;
		}
		//RunWork();
		g_pDMApp->Run(m_pMainWnd->GetSafeHwnd());
		bRet = true;
	} while (false);
	return bRet;
}

bool EDMain::UnInitMain()
{
	return true;
}

bool EDMain::RunPrepare()
{
	bool bRet = false;
	do 
	{
		typedef enum PROCESS_DPI_AWARENESS
		{
			PROCESS_DPI_UNAWARE = 0,
			PROCESS_SYSTEM_DPI_AWARE = 1,
			PROCESS_PER_MONITOR_DPI_AWARE = 2
		} PROCESS_DPI_AWARENESS;

		typedef HRESULT(__stdcall * PFN_GetProcessDpiAwareness) (HANDLE, PROCESS_DPI_AWARENESS*);
		typedef HRESULT(__stdcall * PFN_SetProcessDpiAwareness) (PROCESS_DPI_AWARENESS);

		HMODULE hSHCoreDLL = LoadLibraryW(L"shcore.dll");
		if (hSHCoreDLL != NULL)
		{
			PFN_GetProcessDpiAwareness _GetProcessDpiAwareness = (PFN_GetProcessDpiAwareness)GetProcAddress(hSHCoreDLL, "GetProcessDpiAwareness");
			if (_GetProcessDpiAwareness)
			{
				HANDLE curProcess = GetCurrentProcess();
				PROCESS_DPI_AWARENESS backupValue = PROCESS_DPI_UNAWARE;
				HRESULT hr = _GetProcessDpiAwareness(curProcess, &backupValue);
				if (hr == S_OK)
				{
					PFN_SetProcessDpiAwareness _SetProcessDpiAwareness = (PFN_SetProcessDpiAwareness)GetProcAddress(hSHCoreDLL, "SetProcessDpiAwareness");
					if (_SetProcessDpiAwareness)
					{
						_SetProcessDpiAwareness(PROCESS_SYSTEM_DPI_AWARE);

						HDC screen = GetDC(0);
						int dpiX = GetDeviceCaps(screen, LOGPIXELSX);
						double scale = (double)dpiX / 96.0;
						ReleaseDC(0, screen);

						_SetProcessDpiAwareness(backupValue);

						if (scale >= 1.8)
						{
//#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
//							QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
//#endif
						}
					}
				}
			}

			FreeLibrary(hSHCoreDLL);
		}

		bRet = true;
	} while (false);
	return bRet;
}

bool EDMain::RunMainUI()
{
	bool bRet = false;
	do 
	{
#ifdef _DEBUG
	#define RESLOADFROMDIR
#endif // _DEBUG
		
#ifdef RESLOADFROMDIR
		if (!DMSUCCEEDED(g_pDMApp->LoadResPack((WPARAM)(L"../../../EDesigner/Res/EDesignerRes"), NULL, NULL)))
			break;
#else
 		g_pDMApp->SetDefRegObj(DMResZipImpl::GetClassNameW(), DMREG_Res);// 设置使用内置的zip解析Res方式
 		DMResZipParam zipres(NULL, MAKEINTRESOURCE(IDR_UIZIPRES), L"UIZip");
 		g_pDMApp->LoadResPack((WPARAM)(&zipres), NULL, L"DMResZipImpl");				// 路径总是相对于生成目录-zip方式
#endif //RESLOADFROMDIR
				
		if (!DMSUCCEEDED(g_pDMApp->InitGlobal(L"ds_global")))						  // 初始化指定的全局skin、style、默认字体
		{
			break;
		}

		if (!m_pMainWnd->DM_CreateWindow(L"ds_mainwnd",0,0,0,0,NULL,false))		 // 创建主窗口
		{
			break;
		}

		m_pMainWnd->SendMessage(WM_INITDIALOG);
		m_pMainWnd->CenterWindow();
		m_pMainWnd->ShowWindow(SW_SHOW);
		m_pMainWnd->SetActiveWindow();
		bRet = true;
	} while (false);
	return bRet;
}